package ybt.vueelement.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import ybt.vueelement.custom.BaseService;
import ybt.vueelement.entity.SysRole;
import ybt.vueelement.entity.SysUser;
import ybt.vueelement.repository.SysUserRepository;
import ybt.vueelement.security.User2;

@Service
public class SysUserService extends BaseService<SysUser, Integer> implements UserDetailsService {
	@Autowired
	private SysUserRepository userDAO;

	public SysUser login(String username, String password) {
		return userDAO.findByUsernameAndPassword(username, password);
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user=userDAO.findByUsername(username);
		if(user==null) {
			throw new UsernameNotFoundException(username);
		}
		List<GrantedAuthority> authorities=new ArrayList<GrantedAuthority>();
		List<SysRole> roles=user.getRoles();
		for (SysRole role : roles) {
			authorities.add(new SimpleGrantedAuthority(role.getCode()));
		}
		return new User2(user.getUsername(), user.getPassword(), user.getName(), authorities);
	}


}
